package com.dlc.felear.xiaoensale.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;

import com.dlc.felear.xiaoensale.R;
import com.dlc.felear.xiaoensale.helper.Session;
import com.dlc.felear.xiaoensale.server.DownloadService;
import com.dlc.felear.xiaoensale.utils.PermissionHandler;
import com.itdlc.android.library.base.BaseActivity;

import java.util.Arrays;


public class FirstActivity extends BaseActivity {
    private static final String TAG = "FirstActivity";

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_first;
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onResume() {
        super.onResume();
        applyPermission();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    public void clickView(View view) {
    }

    /**
     * 检测新版本
     */
    public void syncVersion() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(FirstActivity.this, CheckDeviceActivity.class));
                Intent intent = new Intent(FirstActivity.this, DownloadService.class);
                startService(intent);
                FirstActivity.this.finish();
            }
        }, 5000);

    }


    private void applyPermission() {
        try {
            mPermissionHandler.start(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.ACCESS_FINE_LOCATION});
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, e.getMessage());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mPermissionHandler.onRequestPermissionsResult(requestCode, permissions, grantResults);// 必须有这个调用, mPermissionHandler 才能正常工作
    }


    private final PermissionHandler mPermissionHandler = new PermissionHandler(this) {
        @Override
        protected boolean shouldIgnore(String permission) {
            return false;
        }

        @Override
        protected void onPermissionsDecline(String[] permissions) {
            String msg = "没有获得系统权限: " + Arrays.toString(permissions);
            Log.e(TAG, msg);
            showShortToast(msg);
        }

        @Override
        protected void onAllPermissionGranted() {
            Log.e(TAG, "已获得授权");
            syncVersion();
        }
    };

}
